< previous page page_133 next page >

Page 133
As with any other variable definition, it could be defined as Public or Private depending on your needs. A collection is like an empty file cabinet. You can add objects, remove objects, count the number of objects in it, or reference an object. The Collection class has three methods and one property that you can use:
Add methodAdds items to the collection.
Remove methodDeletes items from the collection using an index or key.
Item methodAccesses a collection element by index or key.
Count propertyReturns the current number of items in the collection.
The key to adding objects to the collection is the Add method. The syntax for this method is shown here:
Sub Add (item as Variant [, key As Variant] [, before As Variant]
    [, after As Variant])
For example, to add a new name object to a collection of names using the person's social security number as the key, you would code the following:
ColEmployees.Add NewName, SSNum
This assumes that the SSNum is a string. If the value that you are using for the key is a number, you must use CStr to convert it to a string. The key value accepts only strings as input. In addition, if you are adding objects to the collection in a particular order, you can use the before and after parameters to specify the exact position to add the object.
Caution
Because Collection objects maintain their numeric index numbers automatically as you add and delete items, the index of a given item will change over time. Do not save an index and expect it to retrieve the same item later in your program. Use keys for this purpose.

Because collections can also contain objects instead of values, you can access any of the object's properties without having to first place it in an object variable. You can reference the properties directly from the collection as in the following:
ColTextInputLines.Item(1).ToolTipText = Please enter your First name.
The reason why this works is in the way Visual Basic processes the statement. It evaluates the expression from left to right. When it comes to the Item method for the collection, it gets the reference to the indexed item and uses it to evaluate the remaining parts of the line. Although this is a faster way of writing code to access the properties of a collection object, if you're going to use more than one property or method of an object in

 
< previous page page_133 next page >

If you like this book, buy it!